package com.devo.icecream.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.telephony.TelephonyManager
import android.telephony.gsm.GsmCellLocation
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresPermission
import androidx.core.app.ActivityCompat
import androidx.core.content.edit
import androidx.core.content.getSystemService
import androidx.lifecycle.lifecycleScope
import com.devo.icecream.AppLogger
import com.devo.icecream.IceCreamApp
import com.devo.icecream.data.APIClient
import com.devo.icecream.utils.LocationUtils
import kotlinx.coroutines.launch

private const val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
        View.SYSTEM_UI_FLAG_IMMERSIVE or
        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

open class BaseActivity : ComponentActivity() {

    @SuppressLint("MissingPermission")
    private val launcher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
        if (it) {//获取位置权限成功
            if (LocationUtils.isGpsEnabled()) {//判断Gps是否可用
                //GPS 可用
                watchLocation()
            } else {
                lifecycleScope.launch {
                    //GPS 不可用
                    queryLocation()
                }
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.decorView.apply {
            systemUiVisibility = uiOptions
            setOnSystemUiVisibilityChangeListener {
                if (it and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
                    systemUiVisibility = uiOptions
                }
            }
        }

        launcher.launch(Manifest.permission.ACCESS_FINE_LOCATION)

    }


    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        window.decorView.systemUiVisibility = uiOptions
    }


    override fun onStop() {
        super.onStop()
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            LocationUtils.unregister()
        }
    }

    @RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    fun watchLocation() {
        LocationUtils.register(
            60_000, 1000,
            object : LocationUtils.OnLocationChangeListener {
                override fun getLastKnownLocation(location: Location?) {
                    AppLogger.w(location.toString())
                    location?.let {
                        IceCreamApp.preferences.edit(true) {
                            putString("location", "%.06f,%.06f".format(it.longitude, it.latitude))
                        }
                    }
                }

                override fun onLocationChanged(location: Location?) {
                    AppLogger.w(location.toString())
                    location?.let {
                        IceCreamApp.preferences.edit(true) {
                            putString("location", "%.06f,%.06f".format(it.longitude, it.latitude))
                        }
                    }
                }

                override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}

            },
        )

    }


    @RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    private suspend fun queryLocation() {
        val telephonyManager = getSystemService<TelephonyManager>()

        val latLng = telephonyManager?.let {
            val cellLoc = it.cellLocation as? GsmCellLocation

            cellLoc?.let { cell ->
                val operator = it.networkOperator
                val mcc = operator.substring(0, 3).toInt()
                val mnc = operator.substring(3).toInt()
                val cid = cell.cid
                val lac = cell.lac
                try {
                    APIClient.getCellInfo(mcc, mnc, lac, cid)
                } catch (e: Exception) {
                    AppLogger.e(e, "获取LBS报错")
                    null
                }
            } ?: ""

        }
        //保存值为000
        IceCreamApp.preferences.edit(true) {
            putString("location", latLng ?: "0.0,0.0")
        }

    }


    override fun onBackPressed() {}

}